package com.zinnaworks.smart_cloud_gamepad;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.os.Vibrator;
import android.os.StrictMode.ThreadPolicy;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.google.anymote.Key;
import com.google.anymote.Key.Code;
import com.zinnaworks.smart_cloud_gamepad.popup.ExitDialogPopup;
import com.zinnaworks.smart_cloud_gamepad.popup.ExitDialogPopup.myOnClickListener;
import com.zinnaworks.smart_cloud_gamepad.popup.OneLineDialogPopup;
import com.zinnaworks.smart_cloud_gamepad.popup.OneLineDialogPopup.myOnPrepearClickListener;
import com.zinnaworks.smart_cloud_gamepad.protocol.ICommandSender;
import com.zinnaworks.smart_cloud_gamepad.widget.DualJoystickView;
import com.zinnaworks.smart_cloud_gamepad.widget.JoyStickClass;
import com.zinnaworks.smart_cloud_gamepad.widget.SoftDpad;

public class MainActivity extends BaseActivity {

	private static final String LOG_TAG = "RemoteActivity";
	private final Handler handler;
	
	Animation translateUpAnim;
	Animation translateDownAnim;
	
	ScalableLayout slidingPage01;
	
	TextView stbName;
	
	ImageView slidingBtn;
	ImageView slidingCloseBtn;
	
	TextView signalName;
	
	TextView latelyPlayGame;
	TextView buy_game;
	
	Button gameGuideBtn;
	Button operationGuideBtn;
	
	ToggleButton effectSound;
	ToggleButton vibrationBtn;
	
	RelativeLayout fakePasswordView;
	
	
	ImageView imagerButton_pairing;
	
	ImageView btn_L1;
	ImageView btn_L2;
	ImageView btn_R1;
	ImageView btn_R2;
	
	ImageView btn_Select;
	ImageView btn_Start;
	
	ImageView btn_Y;
	ImageView btn_X;
	ImageView btn_B;
	ImageView btn_A;
	ImageView btn1;
	
	SoftDpad softDpad;
	
	RelativeLayout layout_joystickL;
	ImageView layout_joystickLImage;
	RelativeLayout layout_joystickR;
	ImageView layout_joystickRImage;
	
	JoyStickClass jsL;
	JoyStickClass jsR;
	
	DualJoystickView dualjoystickview;
	
	boolean isSlidingPage = false;

	public MainActivity() {
		handler = new Handler();
	}
	
	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		 if(android.os.Build.VERSION.SDK_INT > 9){
				ThreadPolicy policy = new ThreadPolicy.Builder().permitAll().build();
				StrictMode.setThreadPolicy(policy);
			}
		 
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main3);
		
		latelyPlayGame = (TextView) findViewById(R.id.lately_play_game);
		latelyPlayGame.setOnClickListener(onPrepareListener);
		
		buy_game = (TextView) findViewById(R.id.buy_game);
		buy_game.setOnClickListener(onPrepareListener);
		
		gameGuideBtn = (Button) findViewById(R.id.gameGuideBtn);
		gameGuideBtn.setOnClickListener(onPrepareListener);
		operationGuideBtn = (Button) findViewById(R.id.operationGuideBtn);
		operationGuideBtn.setOnClickListener(onPrepareListener);
		
		
		slidingPage01 = (ScalableLayout)findViewById(R.id.slidingPage);
		
		translateUpAnim = AnimationUtils.loadAnimation(this, R.anim.slide_up);
		translateDownAnim = AnimationUtils.loadAnimation(this, R.anim.slide_down);
		
		signalName = (TextView) findViewById(R.id.signalName);
		
		slidingBtn = (ImageView)findViewById(R.id.slidingBottomButton);
		
		slidingBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				slidingPage01.setVisibility(View.VISIBLE);
				slidingPage01.startAnimation(translateUpAnim);
				
			}
		});
		
		slidingCloseBtn = (ImageView)findViewById(R.id.slidingTopButton);
		
		slidingCloseBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				slidingPage01.startAnimation(translateDownAnim);
				slidingPage01.setVisibility(View.GONE);
			}
		});
		
		stbName = (TextView)findViewById(R.id.settopName);
		
		effectSound = (ToggleButton)findViewById(R.id.effectSound);
		effectSound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
				SharedPreferences.Editor editor = sharedPreferences.edit();
				editor.putBoolean("effectSound", isChecked);
				editor.commit();
			}
		});
		
		vibrationBtn = (ToggleButton)findViewById(R.id.vibrationBtn);
		vibrationBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
				SharedPreferences.Editor editor = sharedPreferences.edit();
				editor.putBoolean("vibrationBtn", isChecked);
				editor.commit();
			}
		});
		
		fakePasswordView = (RelativeLayout) findViewById(R.id.fakeView);
		
		imagerButton_pairing = (ImageView) findViewById(R.id.imagerButton_pairing);
		
		softDpad = (SoftDpad) findViewById(R.id.SoftDpad);
		
		btn_L1 = (ImageView) findViewById(R.id.imageButtonL1);
		btn_L2 = (ImageView) findViewById(R.id.imageButtonL2);
		btn_R1 = (ImageView) findViewById(R.id.imageButtonR1);
		btn_R2 = (ImageView) findViewById(R.id.imageButtonR2);

		btn_Y = (ImageView) findViewById(R.id.imageButton_Y);
		btn_X = (ImageView) findViewById(R.id.imageButton_X);
		btn_B = (ImageView) findViewById(R.id.imageButton_B);
		btn_A = (ImageView) findViewById(R.id.imageButton_A);
		
		dpadLeft = (ImageView) findViewById(R.id.dpad_left);
		dpadRight = (ImageView) findViewById(R.id.dpad_right);
		dpadTop = (ImageView) findViewById(R.id.dpad_top);
		dpadBottom = (ImageView) findViewById(R.id.dpad_buttom);
		
		btn_Select = (ImageView) findViewById(R.id.imageButtonSelect);
		btn_Start = (ImageView) findViewById(R.id.imageButtonStart);

		
		DisplayMetrics displayMetrics = new DisplayMetrics();
		WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE); 
		 // the results will be higher than using the activity context object or the getWindowManager() shortcut
		wm.getDefaultDisplay().getMetrics(displayMetrics);
		
		ScalableLayout sb = (ScalableLayout) findViewById(R.id.scalableBase);
		sb.getScaleWidth();
		sb.getScaleHeight();
		
		////////////////////////////////////////////
		//
		// stick
		//
		////////////////////////////////////////////
		
		float scaleValue = displayMetrics.widthPixels/sb.getScaleWidth();
		 
		layout_joystickL = (RelativeLayout)findViewById(R.id.layout_joystickL);
		jsL = new JoyStickClass(getApplicationContext()
        		, layout_joystickL, R.drawable.btn_stick_press);
	    jsL.setStickSize((int)(246*scaleValue), (int)(246*scaleValue));
	    jsL.setLayoutSize((int)(246*scaleValue), (int)(246*scaleValue));
	    jsL.setLayoutAlpha(150);
	    jsL.setStickAlpha(100);
	    jsL.setOffset((int)(88*scaleValue));
	    layout_joystickL.setOnTouchListener(onTouchListener);
	    
	    layout_joystickLImage = (ImageView)findViewById(R.id.layout_joystickLImage);

	    layout_joystickR = (RelativeLayout)findViewById(R.id.layout_joystickR);
		jsR = new JoyStickClass(getApplicationContext()
        		, layout_joystickR, R.drawable.btn_stick_press);
		jsR.setStickSize((int)(246*scaleValue), (int)(246*scaleValue));
		jsR.setLayoutSize((int)(246*scaleValue), (int)(246*scaleValue));
		jsR.setLayoutAlpha(150);
		jsR.setStickAlpha(100);
		jsR.setOffset((int)(88*scaleValue));
		layout_joystickR.setOnTouchListener(onTouchListener);
		
		layout_joystickRImage = (ImageView)findViewById(R.id.layout_joystickRImage);
	  
		btn_L1.setOnTouchListener(onTouchListener);
		btn_L2.setOnTouchListener(onTouchListener);
		btn_R1.setOnTouchListener(onTouchListener);
		btn_R2.setOnTouchListener(onTouchListener);
		
		btn_Y.setOnTouchListener(onTouchListener);
		btn_X.setOnTouchListener(onTouchListener);
		btn_B.setOnTouchListener(onTouchListener);
		btn_A.setOnTouchListener(onTouchListener);
		
		btn_Select.setOnTouchListener(onTouchListener);
		btn_Start.setOnTouchListener(onTouchListener);
		
		softDpad.setOnTouchListener(onTouchListener);
		
		Bundle bl = getIntent().getExtras();
		if(bl.getBoolean("SHOW_PASSWORKD_VIEW"))
		{
			fakePasswordView.setVisibility(View.VISIBLE);
		}
		else
		{
			fakePasswordView.setVisibility(View.GONE);
		}
		
		
		checkSoundEffect();
		checkvibration();
	}
	
	
	public OnClickListener onPrepareListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			prepearPopup();
		}
	};
	
	myOnPrepearClickListener prepareListener;
	OneLineDialogPopup preparePopup;
	private void prepearPopup()
	{
		if(prepareListener == null)
		{
			prepareListener = new myOnPrepearClickListener() {
				@Override
				public void onButtonClick(boolean bl) {
					
					preparePopup.cancel();
					prepareListener = null;
				}
			};
		}
		preparePopup = new OneLineDialogPopup(this, prepareListener);
		preparePopup.show();
		preparePopup.setDialogText(getString(R.string.none_text), getString(R.string.popup_prepear_content));
	}
	
	private void checkSoundEffect()
	{
		SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
	    effectSound.setChecked(sharedPreferences.getBoolean("effectSound", false));
	}
	private void checkvibration()
	{
		SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
		vibrationBtn.setChecked(sharedPreferences.getBoolean("vibrationBtn", false));
	}
	
	
	
	private int checkKeyCode = 0;
	private OnTouchListener onTouchListener = new View.OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int action = event.getAction() & MotionEvent.ACTION_MASK;
			
			//아날로그 스틱 
			if(v.getId() == R.id.layout_joystickL || v.getId() == R.id.layout_joystickR)
			{
				JoyStickClass jsc;
				ImageView iv;
				if(v.getId() == R.id.layout_joystickL)
				{
					jsc = jsL;
					iv = layout_joystickLImage;
				}
				else
				{
					jsc = jsR; 
					iv = layout_joystickRImage;
				}

				if(action==MotionEvent.ACTION_DOWN ||action==MotionEvent.ACTION_MOVE)
				{
					iv.setVisibility(View.GONE);
					jsc.drawStick(event);
					int direction = getDirection(jsc);
					
					if(direction == 0)
						return false;
					
					if(checkKeyCode == 0)
						checkKeyCode =direction;
					else if(jsc == jsL)
					{
						if(checkKeyCode != direction+28)
						{
							getCommands().key(Code.valueOf(checkKeyCode),Key.Action.UP);
						}
							
					}
					else if(jsc == jsR)
					{
						if(checkKeyCode != direction+36)
						{
							getCommands().key(Code.valueOf(checkKeyCode),Key.Action.UP);
						}
							
					}
						
					if(jsc == jsL)
						checkKeyCode = direction+28;
					else if(jsc == jsR)
						checkKeyCode = direction+36;
					
					getCommands().key(Code.valueOf(checkKeyCode),Key.Action.DOWN);
					return true;
				}
				else if(action==MotionEvent.ACTION_UP)
				{
					iv.setVisibility(View.VISIBLE);
					jsc.drawStick(event);
					getCommands().key(Code.valueOf(checkKeyCode),Key.Action.UP);
					checkKeyCode = 0;
					return true;
				}
				
			}
			else if(v.getId() == R.id.SoftDpad)
			{
				int x = (int) event.getX();
				int y = (int) event.getY();
//				Log.d(VIEW_LOG_TAG, event.getAction() +"x : "+x + "y : "+y);
				
				
				int move;
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					move =((SoftDpad) v).handleActionDown(x, y);
					translateDirection(move, true);
					comparekeycode(move+18);
//					getCommands().key(Code.valueOf(checkKeyCode),Key.Action.DOWN);
					getCommands().keyPress(Code.valueOf(checkKeyCode));
					return true;
				case MotionEvent.ACTION_MOVE:
					move =((SoftDpad) v).handleActionMove(x, y);
					translateDirection(move, true);
					comparekeycode(move+18);
//					getCommands().key(Code.valueOf(checkKeyCode),Key.Action.DOWN);
					getCommands().keyPress(Code.valueOf(checkKeyCode));
					return true;
				case MotionEvent.ACTION_UP:
					move =((SoftDpad) v).handleActionUp(x, y);
					translateDirection(move, false);
//					comparekeycode(move+18);
					getCommands().key(Code.valueOf(checkKeyCode),Key.Action.UP);
					
					break;
				}
				return true;
			}
			else 
			{
				if(action==MotionEvent.ACTION_DOWN)
				{
					sendGamepadKey(v.getId(),true);
					v.setPressed(true);
					return true;
				}
				else if(action==MotionEvent.ACTION_UP)
				{
					sendGamepadKey(v.getId(),false);
					v.setPressed(false);
					playClick();
					return true;
				}
			}
			return false;
		}
	};
	
	private void sendGamepadKey(int id, boolean isPress){
		int temp=0;
		switch (id) {
		case R.id.imageButtonL1:
			temp = 45;
			break;
		case R.id.imageButtonL2:
			temp = 46;
			break;
		case R.id.imageButtonR1:
			temp = 47;
			break;
		case R.id.imageButtonR2:
			temp = 48;
			break;
		case R.id.imageButton_Y:
			temp = 49;
			break;
		case R.id.imageButton_X:
			temp = 50;
			break;
		case R.id.imageButton_B:
			temp = 51;
			break;
		case R.id.imageButton_A:
			temp = 52;
			break;
		case R.id.imageButtonSelect:
			temp = 53;
			break;
		case R.id.imageButtonStart:
			temp = 54;
			break;

		default:
			break;
		}
		
		comparekeycode(temp);
		
		if(isPress)
			getCommands().key(Code.valueOf(checkKeyCode), Key.Action.DOWN);
		else
			getCommands().key(Code.valueOf(checkKeyCode), Key.Action.UP);
	}
	
	private void comparekeycode(int keyCode)
	{
		if(keyCode != checkKeyCode)
		{
			getCommands().key(Code.valueOf(checkKeyCode), Key.Action.UP);
		}
		checkKeyCode = keyCode;
	}
	
	/**
	 * Translates a direction and a key pressed in an action.
	 *
	 * @param direction the direction of the movement
	 * @param pressed   {@code true} if the key was pressed
	 */
	private int oldD = 0;
	private void translateDirection(int direction,boolean pressed) {
		
		dpadLeft.setVisibility(View.GONE);
		dpadRight.setVisibility(View.GONE);
		dpadTop.setVisibility(View.GONE);
		dpadBottom.setVisibility(View.GONE);
		
		if(oldD == 0)
			oldD = direction;
		
		else if(oldD != direction)
		{
			int tempD = direction;
			direction = oldD;
			pressed = false;
			oldD = tempD;
		}
			
		switch (direction) {
		case 4:
			dpadRight.setVisibility(pressed ? View.VISIBLE : View.GONE);
			break;
		case 2:
			dpadBottom.setVisibility(pressed ? View.VISIBLE : View.GONE);
			break;
		case 3:
			dpadLeft.setVisibility(pressed ? View.VISIBLE : View.GONE);
			break;
		case 1:
			dpadTop.setVisibility(pressed ? View.VISIBLE : View.GONE);
			break;
		default:
			break;
		}
	}

	
	
	private int getDirection(JoyStickClass js){
		int direction = js.get8Direction();
		if(direction == JoyStickClass.STICK_UP) {
			Log.d(LOG_TAG,"Direction : Up");
		} else if(direction == JoyStickClass.STICK_UPRIGHT) {
			Log.d(LOG_TAG,"Direction : Up Right");
		} else if(direction == JoyStickClass.STICK_RIGHT) {
			Log.d(LOG_TAG,"Direction : Right");
		} else if(direction == JoyStickClass.STICK_DOWNRIGHT) {
			Log.d(LOG_TAG,"Direction : Down Right");
		} else if(direction == JoyStickClass.STICK_DOWN) {
			Log.d(LOG_TAG,"Direction : Down");
		} else if(direction == JoyStickClass.STICK_DOWNLEFT) {
			Log.d(LOG_TAG,"Direction : Down Left");
		} else if(direction == JoyStickClass.STICK_LEFT) {
			Log.d(LOG_TAG,"Direction : Left");
		} else if(direction == JoyStickClass.STICK_UPLEFT) {
			Log.d(LOG_TAG,"Direction : Up Left");
		} else if(direction == JoyStickClass.STICK_NONE) {
			Log.d(LOG_TAG,"Direction : Center");
		}
		return direction;
	}

	public void onRelease(Key.Code keyCode) {
		getCommands().key(keyCode, Key.Action.UP);
	}


	public void onTouch(Key.Code keyCode) {
		playClick();
		getCommands().key(keyCode, Key.Action.DOWN);
	}


	
	@Override
	protected void onKeyboardOpened() {
		showActivity(KeyboardActivity.class);
	}

	private void playClick() {
		if(effectSound.isChecked())
		{
			AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
					am.playSoundEffect(AudioManager.FX_KEY_CLICK);
		}
		
		if(vibrationBtn.isChecked()){
			Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
			 // Vibrate for 500 milliseconds
			 v.vibrate(50);
		}
		
	}
	
//	@Override
//	public void onConnectionSuccessful(ICommandSender sender) {
//		super.onConnectionSuccessful(sender);
//		dualjoystickview.setCommandSender(getCommands());
//	} 	


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		ev.getPointerId(0);
		return super.dispatchTouchEvent(ev);
	}
	
	@Override
	public void onConnectionSuccessful(ICommandSender sender)
	{
		super.onConnectionSuccessful(sender);
		imagerButton_pairing.setImageResource(R.drawable.img_paring_state_fine);
		signalName.setText(R.string.connect_signal);
		signalName.setTextColor(Color.parseColor("#73c513"));
		fakePasswordView.setVisibility(View.GONE);
	}
	
	public void onShowDeviceFinder()
	{
		super.onShowDeviceFinder();
	}
	
	@Override
	public void onConnectionStbId(String stbId){
		super.onConnectionStbId(stbId);
		stbName.setText(stbId);
		
	}
	
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}
	
//	Runnable mAction = new Runnable() {
//        @Override public void run() {
////            System.out.println("Performing action...");
//            mHandler.postDelayed(this, 200);
//        }
//    };
	
	myOnClickListener myListener;
	ExitDialogPopup exit;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {

		//하드웨어 뒤로가기 버튼에 따른 이벤트 설정
		case KeyEvent.KEYCODE_BACK:
			if(myListener == null)
			{
				myListener = new myOnClickListener() {
					@Override
					public void onButtonClick(boolean bl) {
						if(bl)
							android.os.Process.killProcess(android.os.Process.myPid());
						else
							exit.cancel();
						
						myListener = null;
					}
				};
			}
			exit = new ExitDialogPopup(this,myListener);
			exit.show();
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
}
